class Game {
    constructor() {
        this.characters = [];
        this.gameTime = { hour: 6, minute: 0, day: 1 };
        this.isRunning = false;
        this.currentScene = '城镇广场';
        this.interactionHistory = [];
        this.selectedCharacter = null;
        this.timeMultiplier = 1;
        this.gameLoop = null;
        
        this.initializeGame();
    }
    
    // 初始化游戏
    initializeGame() {
        this.setupEventListeners();
        this.updateTimeDisplay();
        this.updateSceneDisplay();
    }
    
    // 设置事件监听器
    setupEventListeners() {
        document.getElementById('start-btn').addEventListener('click', () => this.startGame());
        document.getElementById('scene-select-btn').addEventListener('click', () => this.toggleSceneSelect());
        document.getElementById('back-to-game-btn').addEventListener('click', () => this.showSceneSelect());
        
        // 时间速率控制
        document.getElementById('time-multiplier').addEventListener('change', (e) => {
            this.timeMultiplier = parseInt(e.target.value);
            this.restartGameLoop();
        });
    }
    
    // 开始游戏
    startGame() {
        if (this.isRunning) return;
        
        console.log('游戏开始');
        this.isRunning = true;
        this.characters = this.generateCharacters();
        this.updateCharacterDisplay();
        this.updateSceneDisplay(); // 确保场景显示更新
        
        // 启动游戏循环
        this.restartGameLoop();
        
        // 隐藏开始按钮
        document.getElementById('start-screen').style.display = 'none';
        document.getElementById('game-screen').style.display = 'block';
    }
    
    // 生成角色
    generateCharacters() {
        const characters = [];
        const professions = [
            'MINER', 'FARMER', 'BLACKSMITH', 'CHEF', 'WARRIOR', 
            'MAGE', 'ARCHER', 'PRIEST', 'WATER_CARRIER', 'LUMBERJACK',
            'FISHERMAN', 'HERDSMAN', 'FRUIT_GROWER', 'MAYOR'
        ];
        
        // 每个职业生成1-3个角色
        professions.forEach(profession => {
            const count = profession === 'MAYOR' ? 1 : 1 + Math.floor(Math.random() * 3);
            for (let i = 0; i < count; i++) {
                characters.push(new Character(null, profession));
            }
        });
        
        console.log('生成角色数量:', characters.length);
        return characters;
    }
    
    // 更新游戏
    updateGame() {
        this.updateTime();
        this.updateCharacters();
        this.updateCharacterDisplay();
        this.updateTimeDisplay();
        
        // 如果有选中的角色，实时更新其信息显示
        if (this.selectedCharacter) {
            this.updateCharacterInfo();
        }
    }
    
    // 重启游戏循环（用于时间倍速变化时）
    restartGameLoop() {
        if (this.gameLoop) {
            clearInterval(this.gameLoop);
        }
        
        const interval = 1000 / this.timeMultiplier;
        this.gameLoop = setInterval(() => {
            this.updateGame();
        }, interval);
    }
    
    // 更新时间
    updateTime() {
        this.gameTime.minute += this.timeMultiplier;
        if (this.gameTime.minute >= 60) {
            this.gameTime.minute = 0;
            this.gameTime.hour += 1;
            if (this.gameTime.hour >= 24) {
                this.gameTime.hour = 0;
                this.gameTime.day += 1;
            }
        }
    }
    
    // 更新角色
    updateCharacters() {
        this.characters.forEach(character => {
            character.update(this.gameTime, this.timeMultiplier);
            character.makeDecision(this.gameTime, this.characters);
        });
    }
    
    // 更新角色显示
    updateCharacterDisplay() {
        const sceneContainer = document.getElementById('scene-view');
        sceneContainer.innerHTML = '';
        
        console.log('当前场景:', this.currentScene);
        console.log('所有角色位置:', this.characters.map(char => ({
            name: char.name,
            location: char.currentLocation,
            isMoving: char.isMoving,
            profession: char.profession
        })));
        
        const sceneCharacters = this.characters.filter(char => 
            char.currentLocation === this.currentScene && !char.isMoving
        );
        
        console.log('当前场景角色:', sceneCharacters.map(char => char.name));
        
        sceneCharacters.forEach(character => {
            const charElement = document.createElement('div');
            charElement.className = 'character';
            
            const profession = PROFESSIONS[character.profession];
            charElement.style.color = profession?.color || '#000';
            charElement.style.borderColor = profession?.color || '#000';
            
            charElement.innerHTML = `
                <div class="character-name">${character.name}</div>
                <div class="character-profession">${profession?.name || character.profession}</div>
            `;
            
            charElement.addEventListener('click', () => this.selectCharacter(character));
            sceneContainer.appendChild(charElement);
        });
    }
    
    // 选择角色
    selectCharacter(character) {
        this.selectedCharacter = character;
        this.updateCharacterInfo();
    }
    
    // 更新角色信息
    updateCharacterInfo() {
        if (!this.selectedCharacter) return;
        
        const character = this.selectedCharacter;
        const infoContent = document.getElementById('info-content');
        const profession = PROFESSIONS[character.profession];
        
        // 显示物品
        const materials = character.inventory.materials.map(item => 
            `${item.name}×${item.quantity}`
        ).join(', ') || '无';
        
        const food = character.inventory.food.map(item => 
            `${item.name}×${item.quantity}`
        ).join(', ') || '无';
        
        const tools = character.inventory.tools.map(item => 
            `${item.name}×${item.quantity}`
        ).join(', ') || '无';
        
        // 显示家庭存储信息
        const homeFood = character.homeStorage.food.map(f => `${f.name}×${f.quantity}`).join(', ') || '无';
        const homeWater = character.homeStorage.water;
        
        // 显示需求阈值
        const hungerThreshold = Math.round(character.needsThreshold.hunger * 100);
        const thirstThreshold = Math.round(character.needsThreshold.thirst * 100);
        const energyThreshold = Math.round(character.needsThreshold.energy * 100);
        
        infoContent.innerHTML = `
            <p><strong>姓名:</strong> ${character.name}</p>
            <p><strong>年龄:</strong> ${character.age}岁</p>
            <p><strong>职业:</strong> ${profession ? profession.name : character.profession}</p>
            <p><strong>生命值:</strong> ${Math.round(character.health)}/100</p>
            <p><strong>金钱:</strong> ${character.inventory.money}</p>
            <p><strong>位置:</strong> ${character.currentLocation}</p>
            <p><strong>状态:</strong> ${character.currentAction}</p>
            <p><strong>移动中:</strong> ${character.isMoving ? '是' : '否'}</p>
            <p><strong>工作中:</strong> ${character.isWorking ? '是' : '否'}</p>
            <hr>
            <p><strong>需求阈值:</strong></p>
            <p>饥饿: ${hungerThreshold}% | 口渴: ${thirstThreshold}% | 精力: ${energyThreshold}%</p>
            <p><strong>预估耗时:</strong></p>
            <p>进食: ${character.estimatedTime.eat}分钟 | 饮水: ${character.estimatedTime.drink}分钟 | 睡眠: ${character.estimatedTime.sleep}分钟</p>
            <p><strong>Debuff状态:</strong></p>
            <p>${character.debuffs.hungry ? '🔥 饥饿' : ''} ${character.debuffs.thirsty ? '💧 口渴' : ''} ${character.debuffs.sleepy ? '😴 困意' : ''} ${!character.debuffs.hungry && !character.debuffs.thirsty && !character.debuffs.sleepy ? '无' : ''}</p>
            <hr>
            <p><strong>原材料:</strong> ${materials}</p>
            <p><strong>食物:</strong> ${food}</p>
            <p><strong>工具:</strong> ${tools}</p>
            <hr>
            <p><strong>家庭存储:</strong></p>
            <p>食物: ${homeFood}</p>
            <p>水: ${homeWater} 单位</p>
        `;
        
        // 更新需求显示
        this.updateNeedsDisplay();
    }
    
    // 更新需求显示
    updateNeedsDisplay() {
        if (!this.selectedCharacter) return;
        
        const character = this.selectedCharacter;
        const needsContainer = document.getElementById('needs-display');
        
        needsContainer.innerHTML = `
            <div class="need-bar">
                <span>饥饿: ${Math.round(character.needs.hunger)}%</span>
                <div class="bar"><div class="fill" style="width: ${character.needs.hunger}%"></div></div>
            </div>
            <div class="need-bar">
                <span>口渴: ${Math.round(character.needs.thirst)}%</span>
                <div class="bar"><div class="fill" style="width: ${character.needs.thirst}%"></div></div>
            </div>
            <div class="need-bar">
                <span>精力: ${Math.round(character.needs.energy)}%</span>
                <div class="bar"><div class="fill" style="width: ${character.needs.energy}%"></div></div>
            </div>
            <div class="need-bar">
                <span>幸福感: ${Math.round(character.needs.happiness)}%</span>
                <div class="bar"><div class="fill" style="width: ${character.needs.happiness}%"></div></div>
            </div>
        `;
    }
    
    // 更新时间显示
    updateTimeDisplay() {
        const timeDisplay = document.getElementById('game-time');
        timeDisplay.textContent = `第${this.gameTime.day}天 ${String(this.gameTime.hour).padStart(2, '0')}:${String(this.gameTime.minute).padStart(2, '0')}`;
    }
    
    // 更新场景显示
    updateSceneDisplay() {
        const sceneDisplay = document.getElementById('scene-name');
        sceneDisplay.textContent = this.currentScene;
    }
    
    // 显示场景选择
    showSceneSelect() {
        const sceneSelect = document.getElementById('scene-select-screen');
        sceneSelect.style.display = 'block';
        
        const sceneList = document.getElementById('scenes-container');
        sceneList.innerHTML = '';
        
        // 添加家页面按钮
        const homesButton = document.createElement('button');
        homesButton.className = 'btn';
        homesButton.textContent = '查看所有角色的家';
        homesButton.onclick = () => this.showHomesPage();
        sceneList.appendChild(homesButton);
        
        // 添加路程中页面按钮
        const movingButton = document.createElement('button');
        movingButton.className = 'btn';
        movingButton.textContent = '查看路程中的角色';
        movingButton.onclick = () => this.showMovingCharacters();
        sceneList.appendChild(movingButton);
        
        // 主场景定义
        const mainScenes = [
            { name: '城镇广场', hasSubScenes: true },
            { name: '铁矿山', hasSubScenes: false },
            { name: '铜矿山', hasSubScenes: false },
            { name: '河滨', hasSubScenes: false },
            { name: '海滨', hasSubScenes: false },
            { name: '森林', hasSubScenes: false },
            { name: '农场', hasSubScenes: false },
            { name: '牧场', hasSubScenes: false },
            { name: '果林', hasSubScenes: false },
            { name: '魔域', hasSubScenes: true }
        ];
        
        mainScenes.forEach(scene => {
            const sceneCard = document.createElement('div');
            sceneCard.className = 'scene-card';
            
            // 计算当前场景的角色数量
            const characterCount = this.characters.filter(char => 
                char.currentLocation === scene.name && !char.isMoving
            ).length;
            
            if (scene.hasSubScenes) {
                // 有子场景的主场景
                sceneCard.innerHTML = `
                    <h3>${scene.name} (${characterCount})</h3>
                    <p>点击查看子场景</p>
                    <div class="sub-scenes" style="display: none;">
                        ${this.generateSubScenes(scene.name)}
                    </div>
                `;
                
                sceneCard.addEventListener('click', (e) => {
                    if (!e.target.closest('.sub-scene-item')) {
                        const subScenes = sceneCard.querySelector('.sub-scenes');
                        subScenes.style.display = subScenes.style.display === 'none' ? 'block' : 'none';
                    }
                });
            } else {
                // 普通场景
                sceneCard.innerHTML = `
                    <h3>${scene.name} (${characterCount})</h3>
                    <p>点击前往此场景</p>
                `;
                
                sceneCard.addEventListener('click', () => {
                    this.selectScene(scene.name);
                });
            }
            
            sceneList.appendChild(sceneCard);
        });
        
        // 添加子场景点击事件委托
        sceneList.addEventListener('click', (e) => {
            const subSceneItem = e.target.closest('.sub-scene-item');
            if (subSceneItem) {
                const sceneName = subSceneItem.getAttribute('data-scene');
                this.selectScene(sceneName);
            }
        });
    }
    
    // 显示所有角色的家
    showHomesPage() {
        const sceneSelect = document.getElementById('scene-select-screen');
        sceneSelect.style.display = 'block';
        
        const sceneList = document.getElementById('scenes-container');
        sceneList.innerHTML = '';
        
        // 添加返回按钮
        const backButton = document.createElement('button');
        backButton.className = 'btn';
        backButton.textContent = '返回场景选择';
        backButton.onclick = () => this.showSceneSelect();
        sceneList.appendChild(backButton);
        
        // 显示所有角色的家
        const homesHeader = document.createElement('h3');
        homesHeader.textContent = '所有角色的家';
        homesHeader.style.marginTop = '20px';
        sceneList.appendChild(homesHeader);
        
        // 按职业分组显示家
        const homesByProfession = {};
        this.characters.forEach(character => {
            if (!homesByProfession[character.profession]) {
                homesByProfession[character.profession] = [];
            }
            homesByProfession[character.profession].push(character);
        });
        
        Object.entries(homesByProfession).forEach(([profession, characters]) => {
            const professionCard = document.createElement('div');
            professionCard.className = 'scene-card';
            professionCard.style.marginBottom = '15px';
            
            const professionName = PROFESSIONS[profession]?.name || profession;
            professionCard.innerHTML = `
                <h4>${professionName}的家</h4>
            `;
            
            characters.forEach(character => {
                const homeItem = document.createElement('div');
                homeItem.className = 'sub-scene-item';
                homeItem.setAttribute('data-scene', character.currentLocation);
                homeItem.innerHTML = `
                    ${character.name} - ${character.currentLocation}
                `;
                homeItem.addEventListener('click', () => {
                    this.selectScene(character.currentLocation);
                });
                professionCard.appendChild(homeItem);
            });
            
            sceneList.appendChild(professionCard);
        });
    }
    
    // 显示正在移动中的角色
    showMovingCharacters() {
        const sceneSelect = document.getElementById('scene-select-screen');
        sceneSelect.style.display = 'block';
        
        const sceneList = document.getElementById('scenes-container');
        sceneList.innerHTML = '';
        
        // 添加返回按钮
        const backButton = document.createElement('button');
        backButton.className = 'btn';
        backButton.textContent = '返回场景选择';
        backButton.onclick = () => this.showSceneSelect();
        sceneList.appendChild(backButton);
        
        // 显示正在移动中的角色
        const movingHeader = document.createElement('h3');
        movingHeader.textContent = '正在路程中的角色';
        movingHeader.style.marginTop = '20px';
        sceneList.appendChild(movingHeader);
        
        // 获取正在移动中的角色
        const movingCharacters = this.characters.filter(char => char.isMoving);
        
        if (movingCharacters.length === 0) {
            const noMovingText = document.createElement('p');
            noMovingText.textContent = '当前没有角色在移动中';
            noMovingText.style.textAlign = 'center';
            noMovingText.style.color = '#666';
            sceneList.appendChild(noMovingText);
            return;
        }
        
        // 显示每个移动中的角色信息
        movingCharacters.forEach(character => {
            const movingCard = document.createElement('div');
            movingCard.className = 'scene-card';
            movingCard.style.marginBottom = '15px';
            
            const profession = PROFESSIONS[character.profession];
            const professionName = profession?.name || character.profession;
            
            // 计算移动进度百分比
            const progressPercent = Math.round((character.moveProgress / character.moveDuration) * 100);
            
            movingCard.innerHTML = `
                <h4>${character.name} (${professionName})</h4>
                <p>当前位置: ${character.currentLocation}</p>
                <p>目标位置: ${character.targetLocation}</p>
                <p>移动进度: ${progressPercent}%</p>
                <div style="background: #ddd; height: 10px; border-radius: 5px; margin: 5px 0;">
                    <div style="background: #3498db; height: 100%; width: ${progressPercent}%; border-radius: 5px;"></div>
                </div>
            `;
            
            sceneList.appendChild(movingCard);
        });
    }
    
    // 生成子场景
    generateSubScenes(mainScene) {
        const subScenes = {
            '城镇广场': [
                '魔药店', '草药店', '防具店', '武器店', 
                '政府', '铁匠铺', '治安署', '磨坊', '餐厅'
            ],
            '魔域': ['魔兽山', '鬼怪湖', '火焰山', '雪山']
        };
        
        const scenes = subScenes[mainScene] || [];
        return scenes.map(scene => `
            <div class="sub-scene-item" data-scene="${scene}">
                ${scene}
            </div>
        `).join('');
    }
    
    // 选择场景
    selectScene(scene) {
        this.currentScene = scene;
        this.updateSceneDisplay();
        this.updateCharacterDisplay();
        this.hideSceneSelect();
    }
    
    // 隐藏场景选择
    hideSceneSelect() {
        document.getElementById('scene-select-screen').style.display = 'none';
    }
    
    // 切换场景选择显示
    toggleSceneSelect() {
        const sceneSelect = document.getElementById('scene-select-screen');
        if (sceneSelect.style.display === 'block') {
            this.hideSceneSelect();
        } else {
            this.showSceneSelect();
        }
    }
    
    // 添加交互历史
    addInteractionHistory(message) {
        this.interactionHistory.unshift(message);
        if (this.interactionHistory.length > 10) {
            this.interactionHistory.pop();
        }
        this.updateInteractionHistory();
    }
    
    // 更新交互历史
    updateInteractionHistory() {
        const historyContainer = document.getElementById('log-content');
        historyContainer.innerHTML = this.interactionHistory
            .map(msg => `<div class="history-item">${msg}</div>`)
            .join('');
    }
}

// 初始化游戏
const game = new Game();